/*
 * @Copyright: Copyright (c) 2030 吴周海
 * @Author: wzh200x@126.com
 * @Date: 2025-10-10 11:35:00
 * @LastEditors: wzh200x@126.com
 * @LastEditTime: 2025-10-15 17:34:20
 * @FilePath: \gogamewebserver\goGameWebServer\internal\model\entity\cdKeyUseModel.go
 * @Description: CdKeyUse 实体模型
 */
package entity

import (
	"goGameWebServer/internal/common/logger"
	"goGameWebServer/internal/common/utils"
	"goGameWebServer/internal/defines/cerror"
	"goGameWebServer/internal/defines/dataType"
	"goGameWebServer/internal/interfaces"
	"goGameWebServer/internal/manager/databasemanager"

	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/util/gmeta"
)

type CdKeyUseModelData struct {
	gmeta.Meta `orm:"table: cd_key_use"`
	Id         dataType.TypeDataBaseId `orm:"id"`         // ID
	UserId     dataType.TypeDataBaseId `orm:"userId"`     // 使用的用户ID
	Codes      string                  `orm:"codes"`      // 使用过的CDKey
	CreateTime string                  `orm:"createTime"` // 创建时间
}

func (d *CdKeyUseModelData) Reset() {
	d.Id = 0
	d.UserId = 0
	d.Codes = ""
	d.CreateTime = ""
}

type CdKeyUseModel struct {
	EntityModel
}

func (m *CdKeyUseModel) LoadEntityDataFromDB(records interface{}) error {
	base, err := databasemanager.ManagerDatabase().DefaultDataBase()
	if err != nil {
		return err
	}
	if entityData, ok := m.EntityData.(*CdKeyUseModelData); ok {
		one, err := base.GetDb().Model(m.Template).Where("userId", entityData.UserId).One()
		if err != nil {
			return err
		}
		if one == nil {
			return m.Create()
		}
		_ = one.Struct(m.EntityData)
		m.SetEntityDBID(entityData.Id)
		return nil
	}
	return gerror.NewCodef(gcode.New(cerror.ERROR_ENTITY_PROPERTY_INVALID, "", nil), "cd_key_use model data is invalid")
}

func (m *CdKeyUseModel) Create() error {
	if entityData, ok := m.EntityData.(*CdKeyUseModelData); ok {
		entityData.CreateTime = utils.GetNowTimeFormat()
		entityData.Codes = "[]"
		err := m.CreateDataToDB()
		entityData.Id = m.EntityDBID
		if err != nil {
			return err
		}
		logger.LoggerIns().Debug("create cd_key_use success")
		return nil
	}
	return gerror.NewCodef(gcode.New(cerror.ERROR_ENTITY_PROPERTY_INVALID, "", nil), "cd_key_use model create fail, data is invalid")
}

func NewCdKeyUseModel(name string) interfaces.IEntityModel {
	m := &CdKeyUseModel{
		EntityModel: NewEntityModel(name),
	}
	m.SetEntityData(&CdKeyUseModelData{
		Id:         0,
		UserId:     0,
		Codes:      "",
		CreateTime: "",
	})
	m.SetTemplate(m.EntityData)
	return m
}
